// 微信的unionID自动合并用户机制
const slime_core           = require("../../annotation/index.js");

@heard("weixinmp.user_updated").then(function(mew) {

    let wrapper = mew.content[mew.usage];

    @lab(function(lab) {
        // wrapper.user -> unionid; 建微信公共表

        let update_form = wrapper.user;

        return lab.slime.member.@updateWeixinUnionID({
            source: wrapper.source,
            open_id: wrapper.user.openid,
            union_id: wrapper.user.unionid
        }).then(function() {

            return lab.slime.member.@updateMember({

                member_no: "",
                gender: {
                    0: "未知",
                    1: "男",
                    2: "女"
                }[update_form.sex],
                image_url: update_form.headimgurl,
                name: update_form.nickname,
                country: update_form.country,
                province: update_form.province,
                city: update_form.city
            }, {
                idSource: wrapper.source,
                idValue: wrapper.user.openid,
            });
        }).then(function(member) {

            if (wrapper.user.unionid) {
                lab.slime.member.@mergeWeixinUserByUnionID({
                    member,
                    union_id: wrapper.user.unionid,
                    wrapper_source : wrapper.source
                }).pipe(this);
            } else {
                this.next(member)
            }

        }).rejected(function(error){
            @error(error)
        })

    }).rejected(function(error) {
        @error(error);
    })
});

@heard(["workwx.customer_updated","workwx.customer_created"]).then(function(mew) {
    let wrapper = mew.content[mew.usage];
    
    @lab(function(lab) {
        let update_form = wrapper.customer;

        @.async(function () {

            if (update_form.union_id) {

                return lab.slime.member.@updateWeixinUnionID({
                    source: wrapper.source,
                    open_id: update_form.external_uid,
                    union_id: update_form.union_id
                })

            } else {
                this.next();
            }
            
        }).then(function() {

            return lab.slime.member.@updateMember({
                gender: {
                    "1": "男",
                    "2": "女"
                }[update_form.gender.toString()] || "未知",
                image_url: update_form.avatar,
                name: update_form.name,
            }, {
                idSource: wrapper.source,
                idValue: update_form.external_uid,
            });

        }).then(function(member) {
            if (update_form.union_id) {
                lab.slime.member.@mergeWeixinUserByUnionID({
                    member,
                    union_id: update_form.union_id,
                    wrapper_source : wrapper.source
                }).pipe(this);
            } else {
                this.next()
            }
        })
    })
})

@heard("wechat.user_updated").then(function(mew) {

    let wrapper = mew.content[mew.usage];

    @lab(function(lab) {
        // wrapper.user -> unionid; 建微信公共表

        let update_form = wrapper.user;

        return @.async(function () {

            if (update_form.union_id) {

                return lab.slime.member.@updateWeixinUnionID({
                    source: wrapper.source,
                    open_id: update_form.id,
                    union_id: update_form.union_id
                })

            } else {
                this.next();
            }
            
        }).then(function() {
            
            // 这里就要去记录epoch number，即变更记录号，当前session的变更记录号 > 记录的变更记录号，再变更；
            return lab.slime.member.@updateMember({

                member_no: update_form.member_id,
                gender: {
                    "not_set": "未知",
                    "male": "男",
                    "female": "女"
                }[update_form.gender],
                image_url: update_form.avatar_url,
                name: update_form.nickname,
                phone: update_form.phone,
                country: update_form.country,
                province: update_form.province,
                city: update_form.city,
                district: update_form.district
            }, {
                idSource: wrapper.source,
                idValue: wrapper.user.id,
            });

        }).then(function(member) {
            if (wrapper.user.union_id) {
                lab.slime.member.@mergeWeixinUserByUnionID({
                    member,
                    union_id: wrapper.user.union_id,
                    wrapper_source : wrapper.source
                }).pipe(this);
            } else {
                this.next(member)
            }
        })

    }).rejected(function(error) {
        @error(error);
    })
});
module.exports = function(lab){
    return {
        "@mergeWeixinUserByUnionID" : function ({member, union_id, wrapper_source}) {
            return lab.sqlite.find("slime_weixin_union_ids",  { union_id }).then(function({ records }) {

                this.next(records.filter(({ source }) => source != wrapper_source));
                
            }).then(function(records) {

                return @.async.all(records, function({source,open_id}) {
                    return lab.slime.member.@queryMember({
                        idSource: source,
                        idValue: open_id
                    }).then(function(targetMember) {
                        if (targetMember && targetMember.main_id != member.main_id) {
                            return lab.slime.member.@mergeMember(member, targetMember)
                        } else {
                            this.next()
                        }
                    })
                })

            }).then(function () {
                // TODO : member.ouid 是否包含phone的source
                if (slime_core.sources["phone"] && member.phone){
                    @.async(function () {
                        lab.find("slime_member_ids", member.id).pipe(this);
                    }).then(function (member_id) {
                        this.pool.member_id = member_id;
                        lab.find("slime_member_ids",{
                            phone : member.phone,
                            ouid  : member.ouid
                        }).pipe(this);
                    }).then(function (phone_member_id) {
                        if (phone_member_id) {

                            if (phone_member_id.main_id == this.pool.member_id.main_id) {
                                // 两者一致，不合并
                                this.next();
                            } else {
                                // 两者不一致，合并
                                lab.find("slime_members",phone_member_id.main_id).pipe(this);
                            }

                        } else {
                            this.next();
                        }
                    }).then(function (phone_member) {
                        
                        if (phone_member) {
                            lab.slime.member.@mergeMember(member, phone_member).pipe(this);
                        } else {
                            this.next();
                        }
                        
                    }).pipe(this);
                } else {
                    this.next();
                }
            })
        },
        "@updateWeixinUnionID": function({ source, open_id, union_id }) {
            return lab.find("slime_weixin_union_ids", {
                source,
                open_id
            }).then(function(result) {
                if (result) {
                    result.union_id = union_id
                    return lab.update("slime_weixin_union_ids", result)
                } else {
                    return lab.create("slime_weixin_union_ids", {
                        source,
                        open_id,
                        union_id
                    })
                }
            })
        },
        "@getWeixinUnionID": function({ union_id, source }) {

            var form = { union_id };

            if (source) {
                form.source = source;
            }

            return lab.sqlite.find("slime_weixin_union_ids",  form).then(function({ records }) {
                this.next(records)
            })
        }
    }
}
